package com.edou.base.util;

import java.awt.Color;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;
import java.util.Random;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;

import com.edou.base.dto.BaseCondition;

import sun.misc.BASE64Decoder;

public abstract class CommonUtil {
	
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	private static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
	public static final String FULL_DATEFORMAT = "yyyy-MM-dd HH:mm:ss";
	public static final String SHORT_DATEFORMAT = "yyyy-MM-dd";
	public static final String SHORT_TIMEFORMAT = "HH:mm:ss";
	static String regEx = "[\u4e00-\u9fa5]";
	static Pattern pat = Pattern.compile(regEx);
	
	private static String[] weeks = new String[]{"周日","周一","周二","周三","周四","周五","周六"};
	
	private static Calendar calendar = Calendar.getInstance(Locale.CHINA);
	private static final int BUFFER_SIZE = 2048000;
	
	/**
	 * String 转换 Long 数组
	 */
	public static Long[] stringToLongArray(String ids){
		String []idArr = ids.split("-");
		Long []idList = new Long[idArr.length];
		for(int i = 0;i<idArr.length;i++){
			if(StringUtils.isNotBlank(idArr[i])){
				try {
					idList[i] = Long.valueOf(idArr[i]);
				} catch (NumberFormatException e) {
					continue;
				}
			}
		}
		return idList;
	}
	
	public static String formatDate(Date d){
		return d!=null?sdf.format(d):null;
	}
	
	public static String formatDate(Date d,String pattern){
		if(d == null){
			return "";
		}
		sdf.applyPattern(pattern);
		return sdf.format(d);
	}
	
	public static Date parseDate(String date, String pattern) {
		sdf.applyPattern(pattern);
		Date d = null;
		try {
			d = sdf.parse(date);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return d;
	}
	
	public static Date parseDate(String date, String pattern,Locale locale) {
		Date result = null;
		try {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern,locale);
			result = simpleDateFormat.parse(date);
			return result;
		} catch (ParseException e) {
			try {
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd",locale);
				result = simpleDateFormat.parse(date);
				return result;
			} catch (ParseException e1) {
				e1.printStackTrace();
				return result;
			}
		}
		
	}
	
	/**
	 * 获取两个日期之间的天数
	 * @param d1 开始日期
	 * @param d2 结束日期
	 * @return
	 */
	public static int getDaysBetween(java.util.Calendar d1,java.util.Calendar d2) {
//		if (d1.after(d2)) { // swap dates so that d1 is start and d2 is end   
//			java.util.Calendar swap = d1;
//			d1 = d2;
//			d2 = swap;
//		}
		int days = d2.get(java.util.Calendar.DAY_OF_YEAR) - d1.get(java.util.Calendar.DAY_OF_YEAR);
		int y2 = d2.get(java.util.Calendar.YEAR);
		if (d1.get(java.util.Calendar.YEAR) != y2) {
			d1 = (java.util.Calendar) d1.clone();
			do {
				days += d1.getActualMaximum(java.util.Calendar.DAY_OF_YEAR);
				d1.add(java.util.Calendar.YEAR, 1);
			} while (d1.get(java.util.Calendar.YEAR) != y2);
		}
		return days;
	}
	
	/**
	 * 获取两个日期之间的天数
	 * @param d1 开始日期
	 * @param d2 结束日期
	 * @return
	 */
	public static int getDaysBetween(Date date1,Date date2) {
		Integer days=null;
		try {
			Calendar d1 = Calendar.getInstance();
			d1.setTime(date1);
			Calendar d2 = Calendar.getInstance();
			d2.setTime(date2);
			
			days = d2.get(java.util.Calendar.DAY_OF_YEAR) - d1.get(java.util.Calendar.DAY_OF_YEAR);
			int y2 = d2.get(java.util.Calendar.YEAR);
			if (d1.get(java.util.Calendar.YEAR) != y2) {
				d1 = (java.util.Calendar) d1.clone();
				do {
					days += d1.getActualMaximum(java.util.Calendar.DAY_OF_YEAR);
					d1.add(java.util.Calendar.YEAR, 1);
				} while (d1.get(java.util.Calendar.YEAR) != y2);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return days;
	}
	
	/**
	 * 设置天数
	 * @param date
	 * @param day
	 * @return
	 */
	public static Date setDay(Date date,int day){
		calendar.setTime(date);
//		calendar.set(Calendar.HOUR_OF_DAY, 0);
//		calendar.set(Calendar.MINUTE, 0);
//		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.DAY_OF_MONTH, day);
		return calendar.getTime();
	}
	
	/**
	 * 获取是周几 1表示周1 
	 * @param d
	 * @return
	 */
	public static int getChineseWeekNum(Date d){
		calendar.setTime(d);
		
		int week = calendar.get(Calendar.DAY_OF_WEEK);
		
		week = week - 1;	//默认周日为1
		
		return week;
	}
	
	public static int getDay(Date date){
		calendar.setTime(date);
		return calendar.get(Calendar.DAY_OF_MONTH);
	}
	
	/**
	 * 获取小时
	 * @param d
	 * @return
	 */
	public static int getHour(Date d){
		calendar.setTime(d);
		return calendar.get(Calendar.HOUR_OF_DAY);
	}
	
	/**
	 * 获取星期几
	 * @param num
	 * @return
	 */
	public static String getChineseWeekNameByNum(int num){
		return weeks[num];
	}
	
	/**
	 * 获取日期
	 * @param d
	 * @return
	 */
	public static String getDate(Date d) {
		return sdf2.format(d);
	}
	
	/**
	 * 获取当天起始时间 00:00
	 * @return
	 */
	public static Date getCurrenDateStart() {
		Date now = new Date();
		calendar.setTime(now);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE,0);
		calendar.set(Calendar.SECOND, 0);
		
		return calendar.getTime();
	}
	
	/**
	 * 获取当天结束时间 23:59:59
	 * @return
	 */
	public static Date getCurrenDateEnd() {
		Date now = new Date();
		calendar.setTime(now);
		calendar.set(Calendar.HOUR_OF_DAY, 23);
		calendar.set(Calendar.MINUTE,59);
		calendar.set(Calendar.SECOND, 59);
		
		return calendar.getTime();
	}
	
	/**
	 * 获取当周最后一天日期
	 * @param now
	 * @return
	 */
	public static Date getWeekEnd(Date now) {
		int addNum = 0;
		int nowWeek = getChineseWeekNum(now);
		if(nowWeek == 0){
			addNum = 1;
		}else{
			addNum = 7-nowWeek+1;
		}
		 
		calendar.setTime(now);
		calendar.add(Calendar.DAY_OF_YEAR, addNum);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE,0);
		calendar.set(Calendar.SECOND, 0);
		return calendar.getTime();
	}
	
	/**
	 * 获取当周第一天日期
	 * @param startDate
	 * @return
	 */
	public static Date getWeekStart(Date startDate) {
		int week = getChineseWeekNum(startDate);
		int subNum = 0;
		if(week == 0){
			subNum = -6;
		}else{
			subNum = -week + 1;
		}
		calendar.setTime(startDate);
		calendar.add(Calendar.DAY_OF_YEAR, subNum);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE,0);
		calendar.set(Calendar.SECOND, 0);
		return calendar.getTime();
	}
	
	/**
	 * 增加目标日期天数
	 * @param targetDate
	 * @param addDays
	 * @return
	 */
	public static Date addTargetDateDay(Date targetDate,int addDays){
		Calendar calendar = Calendar.getInstance(Locale.CHINA);
		calendar.setTime(targetDate);
		calendar.add(Calendar.DAY_OF_YEAR, addDays);
		return calendar.getTime();
	}
	
	/**
	 * 获取指定日期月份有多少天
	 * @return
	 */
	public static int getMonthHaveDayCount(Date date){
		int result = 0;
		Calendar calendar1 = Calendar.getInstance(Locale.CHINA);
		calendar1.setTime(date);
		
		Calendar calendar2 = Calendar.getInstance(Locale.CHINA);
		calendar2.clear(); 
		calendar2.set(Calendar.YEAR,calendar1.get(Calendar.YEAR)); 
		calendar2.set(Calendar.MONTH,calendar1.get(Calendar.MONTH));       
		result = calendar2.getActualMaximum(Calendar.DAY_OF_MONTH);
		return result;
	}
	
	/**
	 * 检查是否需要转义符号
	 * @param condition
	 */
	public static void checkEscapeValue(BaseCondition condition){
		Field[] fields = condition.getClass().getDeclaredFields();
		for(Field field : fields){
			Object val = ReflectionUtil.getFieldValue(condition, field.getName());
			if(val instanceof String){
				//只对string类型的数据进行like检查
				String str = val.toString();
				if(str.indexOf("%") != -1 || str.indexOf("_") != -1){
					condition.setEscapeSymbol(true);
				}
			}
		}
	}
	
	/**
	 * 上传文件
	 * 
	 * @param src
	 *            源文件
	 * @param dst
	 *            目标文件
	 */
	public static void uploadFile(File src, File dst) {
		try {
			InputStream in = null;
			OutputStream out = null;
			try {
				in = new BufferedInputStream(new FileInputStream(src),BUFFER_SIZE);
				out = new BufferedOutputStream(new FileOutputStream(dst),BUFFER_SIZE);
				byte[] buffer = new byte[BUFFER_SIZE];
				int length = 0;
				while ((length = in.read(buffer)) != -1) {
					out.write(buffer, 0, length);
				}
				out.flush();
			} finally {
				IOUtils.closeQuietly(in);
				IOUtils.closeQuietly(out);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取单元格中的值
	 * @param cell
	 * @return
	 */
	public static String getCellValue(HSSFCell cell) {
		String val = null;
		if(null != cell){
			int cellType = cell.getCellType();
			switch(cellType){
			case HSSFCell.CELL_TYPE_BLANK:
				break;
			case HSSFCell.CELL_TYPE_FORMULA:
				if(HSSFDateUtil.isCellDateFormatted(cell)){
					val = CommonUtil.formatDate(cell.getDateCellValue(),"yyyy.M.d").trim();
				}else{
					val =cell.getCellFormula().trim();
				}
				break;
			case HSSFCell.CELL_TYPE_BOOLEAN:
				val = String.valueOf(cell.getBooleanCellValue());
				break;
			case HSSFCell.CELL_TYPE_NUMERIC:
				if(HSSFDateUtil.isCellDateFormatted(cell)){
					val = CommonUtil.formatDate(cell.getDateCellValue(),"yyyy.M.d").trim();
				}else{
					BigDecimal bigDecimal = new BigDecimal(cell.getNumericCellValue());
					val = bigDecimal.toPlainString();
				}
				break;
			case HSSFCell.CELL_TYPE_STRING:
				val = cell.getStringCellValue().trim();
				break;
			default:
					break;
			}
		}
		if(val != null){
			val = val.trim();
		}
		return val;
	}
	
	/**
	 * 将字符串中包含"'"的字符替换为空白
	 * @param target		目标字符串
	 * @return
	 */
	public static String replaceTargetForBlank(String target){
		if(StringUtils.isBlank(target)){
			return "";
		}
		return StringUtils.replace(target, "'","");
	}
	
	/**
	 * 将图片字符串存储于本地磁盘中
	 * @param imgStr Base64加码的图片字符串
	 * @param destFilePath 目标文件绝对路径
	 * @return
	 */
	public static void saveBase64ImageToFile(String imgStr,String destFilePath) {
		//对字节数组字符串进行Base64解码并生成图片
		if (imgStr == null || "".equals(imgStr)) {
			//图像数据为空
			return;
		}
		BASE64Decoder decoder = new BASE64Decoder();
		OutputStream os = null;
		try {
			//Base64解码
			byte[] b = decoder.decodeBuffer(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {
					//调整异常数据
					b[i] += 256;
				}
			}
			os = new FileOutputStream(destFilePath);    
			os.write(b);
			os.flush();
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			IOUtils.closeQuietly(os);
		}
	}
	
	/**
	  * 将文本转成HTML格式
	  *
	  * @return String
	  */
	 public static String convertTextToHtml(String text) {
	  if(StringUtils.isNotBlank(text)){
	   text=text.replace("\r\n", "<br/>");
	   text=text.replace("\n", "<br/>");
	   text=text.replace(" ", "&nbsp;");
	   return text;
	  }
	  return null;
	 }
	
	 public static void main(String[] args) {
		String imgStr = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8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7f/AGnxXHGjbilvsAPRSWYk/kBn/wCvXu19MlpBdTu21VQkn0wGr5Y12/OratfXhUqJ5DIz/wASJn5V+uOn/wBaqprqJmShyFChAXBCMeSEB5Y/Ug/X8af5ZcoC+AepJGVXjBz0JJAP5e+WgEq7zk4Ygvt4wMcD6nkew78UjSoVDBQS53uoB2gYyB64PJPryK0JHFg6HYh2qnQjggfdUexyPz9qruXntXeTbukQk46D5xj9KfEHnvFU4EdtIskn/TR89/pwKa8R3zYGF3FfyQH+lIY+x2+UEYjAMkYySP4dw/UVNsnRUWKSMIEXAJPoKrWny33l/eH2gnH1IWtXTihsU3ltwLA9ezEVSEzKkAJj9Sw57/dBqR0C20LDO7yGOfqwzRRUgPIG6NcDH2qNenbc9VbKRiZYCfkX96vqG34yPwoopgaNqxZyD/HF5p/3uOabG5kaFWAKyxsWGOMgNz7dKKKoR7N8Fb6ea2uoJHzGjFgMdz1r12Pov+6KKK557miOZ8dSvF4U1cocH7K//oLV8xXBZzbq7MVljaV1zgZw3+H8/U0UVcNhMggVWeDcNxkhMr5J5PzcfTj/ADk1HeyOiXEysRIGyD7560UVb2EVbYmKzlCnGYv6p/jV5kCi4IznzJO//TM0UUkBWtiXvmdvvboz+bipDK8TyIjYUO2Bj3NFFAj/2Q==";
		CommonUtil.saveBase64ImageToFile(imgStr, "d:\\test.jpg");
	 }
	 
	/**
	 * 读取源文件内容
	 * 
	 * @param filename
	 *            String 文件路径
	 * @throws IOException
	 * @return byte[] 文件内容
	 */
	public static byte[] readFile(String filename) throws IOException {

		File file = new File(filename);
		if (!isNotBlank(filename)) {
			throw new NullPointerException("无效的文件路径");
		}
		long len = file.length();
		byte[] bytes = new byte[(int) len];
		BufferedInputStream bufferedInputStream = null;
		try{
			bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
			int r = bufferedInputStream.read(bytes);
			if (r != len)
				throw new IOException("读取文件不正确");
		}finally{
			IOUtils.closeQuietly(bufferedInputStream);
		}
		
		return bytes;
	}

	/**
	 * 将数据写入文件
	 * 
	 * @param data
	 *            byte[]
	 * @throws IOException
	 */
	public static void writeFile(byte[] data, String filename)
			throws IOException {
		File file = new File(filename);
		boolean success = file.getParentFile().mkdirs();
		//创建文件夹成功
		if (success) {
			BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
					new FileOutputStream(file));
			bufferedOutputStream.write(data);
			bufferedOutputStream.close();
		}
	}

	/**
	 * 判断是否包含中文
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isContainsChinese(String str) {
		Matcher matcher = pat.matcher(str);
		boolean flg = false;
		if (matcher.find()) {
			flg = true;
		}
		return flg;
	}

	/**
	 * 检查字符串是否为空或NULL
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isNotBlank(String s) {
		if (null == s) {
			return false;
		}
		if (s.trim().equals("")) {
			return false;
		}
		return true;
	}

	/**
	 * 判断是否为INT
	 * 
	 * @param expression
	 * @return
	 */
	public static boolean isInt(Object expression) {
		if (expression != null) {
			try {
				Integer.parseInt(expression.toString());
				return true;
			} catch (Exception e) {
				return false;
			}
		}
		return false;
	}

	/**
	 * 判读是否为DOUBLE
	 * 
	 * @param expression
	 * @return
	 */
	public static boolean isDuble(Object expression) {
		if (expression != null) {
			try {
				Double.parseDouble(expression.toString());
			} catch (Exception e) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 判断给定的字符串数组中的数据是不是都为数值型
	 * 
	 * @param array
	 *            字符串数组
	 * @return 是否成功
	 */
	public static boolean isIntArray(String[] array) {
		if (array == null) {
			return false;
		}
		if (array.length < 1) {
			return false;
		}
		for (String string : array) {
			if (!isInt(string)) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 返回系统当前时间
	 * 
	 * @return String 当前时间
	 */
	public static String getNowTime() {
		return dateFormat(getNowDate(), FULL_DATEFORMAT);
	}

	/**
	 * 获取指定的时间yyyy-MM-dd HH:mm:ss格式的字符串
	 * 
	 * @param date
	 * @return
	 */
	public static String getFullDateString(Date date) {
		return dateFormat(date, FULL_DATEFORMAT);
	}

	/**
	 * 格式化内容，只保留前n个字符，并进一步确认是否要在后面加上...
	 * 
	 * @param str
	 *            要处理的字符串
	 * @param num
	 *            保留的字数
	 * @param hasDot
	 *            是否显示...
	 * @return
	 */

	public static String format(String str, int num, boolean hasDot) {
		if (str == null)
			return "";
		else {
			if (str.getBytes().length < num * 2)
				return str;
			else {
				byte[] ss = str.getBytes();
				byte[] bs = new byte[num * 2];
				for (int i = 0; i < bs.length; i++) {
					bs[i] = ss[i];
				}
				String subStr = CommonUtil.substring(str, num * 2);
				if (hasDot) {
					subStr = subStr + "...";
				}
				return subStr;
			}
		}
	}

	/**
	 * 取出指定长度字符串
	 * 
	 * @param s
	 *            字符串
	 * @param maxLength
	 *            长度
	 * @return
	 */
	public static String substring(String s, int maxLength) {
		if (s.getBytes().length <= maxLength)
			return s; 
		int i = 0; 
		for (int k = 0; k < maxLength && i < s.length(); i++, k++) {
			if (s.charAt(i) > '一') {
				k++;
			}
		}
		if (i < s.length()) {
			s = s.substring(0, i);
		}
		return s;
	}

	/**
	 * 转换对象为字符串
	 * 
	 * @param s
	 *            对象
	 * @return 如果为空则返回""
	 */
	public static String null2String(Object s) {
		return s == null ? "" : s.toString().trim();
	}

	/**
	 * 随机生成指定位数且不重复的字符串.去除了部分容易混淆的字符，如1和l，o和0等，
	 * 
	 * 随机范围1-9 a-z A-Z
	 * 
	 * @param length
	 *            指定字符串长度
	 * @return 返回指定位数且不重复的字符串
	 */
	public static String getRandomString(int length) {
		StringBuffer bu = new StringBuffer();
		String[] arr = { "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c",
				"d", "e", "f", "g", "h", "i", "j", "k", "m", "n", "p", "q",
				"r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C",
				"D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "P",
				"Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
		Random random = new Random();
		while (bu.length() < length) {
			String temp = arr[random.nextInt(57)];
			if (bu.indexOf(temp) == -1) {
				bu.append(temp);
			}
		}
		return bu.toString();
	}

	/**
	 * 获取某个范围内的随机整数
	 * 
	 * @param sek
	 *            随机种子
	 * @param start
	 *            最小范围
	 * @param max
	 *            最大范围
	 * @return 整数
	 */
	public static int getRandomInt(int sek, int min, int max) {

		Random random = new Random();

		int temp = 0;

		do {
			temp = random.nextInt(sek);
		} while (temp < min || temp > max);

		return temp;
	}

	/**
	 * 转换对象为INT
	 * 
	 * @param s
	 *            对象
	 * @return 如果为空则返回-1
	 */
	public static int null2Int(Object s) {
		return null2Int(s, -1);
	}

	/**
	 * 转换对象为INT
	 * 
	 * @param object
	 *            对象
	 * @param def
	 *            失败默认值
	 * @return INT值
	 */
	public static int null2Int(Object object, int def) {

		if (object != null) {
			try {
				return Integer.parseInt(object.toString());
			} catch (Exception e) {
			}
		}
		return def;
	}

	/**
	 * 转换对象为Long
	 * 
	 * @param object
	 *            对象
	 * @param def
	 *            失败默认值
	 * @return Long值
	 */
	public static Long null2Long(Object object, Long def) {

		if (object != null) {
			try {
				return Long.parseLong(object.toString());
			} catch (Exception e) {
			}
		}
		return def;
	}

	/**
	 * 转换对象为Float
	 * 
	 * @param s
	 *            对象
	 * @return 如果为空则返回-1
	 */
	public static float null2Float(Object s) {
		return null2Float(s, -1);
	}

	/**
	 * 转换对象为Float
	 * 
	 * @param s
	 *            对象
	 * @return 如果为空则返回-1
	 */
	public static float null2Float(Object s, float defValue) {
		if (s != null) {
			try {
				return Float.parseFloat(s.toString());
			} catch (Exception e) {
			}
		}
		return defValue;
	}

	/**
	 * 转换对象为Float
	 * 
	 * @param s
	 *            对象
	 * @return 如果为空则返回-1
	 */
	public static double null2Double(Object s, double defValue) {
		if (s != null) {
			try {
				return Double.parseDouble(s.toString());
			} catch (Exception e) {
			}
		}
		return defValue;
	}

	/**
	 * object型转换为bool型
	 * 
	 * @param expression
	 *            要转换的对象
	 * @param defValue
	 *            缺省值
	 * @return 转换后的bool类型结果
	 */
	public static boolean null2Boolean(Object expression, boolean defValue) {
		try {
			return Boolean.parseBoolean(null2String(expression));
		} catch (Exception e) {
			return defValue;
		}
	}

	/**
	 * 按照指定方式格式化时间
	 * 
	 * @param date
	 *            时间
	 * @param type
	 *            格式
	 * @return
	 */
	public static String dateFormat(Date date, String type) {
		SimpleDateFormat sdf = new SimpleDateFormat(type);
		return sdf.format(date);
	}

	/**
	 * 按照指定方式格式化时间
	 * 
	 * @param type
	 *            格式
	 * @return
	 */
	public static String dateFormat(String type) {
		return dateFormat(getNowDate(), type);
	}

	/**
	 * 返回系统当前时间的date对象
	 * 
	 * @return
	 */
	public static Date getNowDate() {
		return new Date();
	}

	/**
	 * 返回系统当前日期
	 * 
	 * @return String 日期
	 */
	public static String getNowShortDate() {
		return dateFormat(getNowDate(), SHORT_DATEFORMAT);
	}

	/**
	 * 返回日期
	 * 
	 * @param date
	 * @return
	 */
	public static String getShortDate(Date date) {
		return dateFormat(date, SHORT_DATEFORMAT);
	}

	/**
	 * 返回系统当前时间
	 * 
	 * @return 时间
	 */
	public static String getNowShortTime() {
		return dateFormat(getNowDate(), SHORT_TIMEFORMAT);
	}

	/**
	 * 判断时间格式
	 * 
	 * @param date
	 * @param format
	 * @return
	 */
	public static boolean checkDate(String date, String format) {
		SimpleDateFormat df = new SimpleDateFormat(format);
		try {
			df.parse(date);
		} catch (Exception e) {
			// 如果不能转换,肯定是错误格式
			return false;
		}
		return true;
	}

	/**
	 * 计算时间差 (时间单位,开始时间,结束时间)<br>
	 * s - 秒,m - 分,h - 时,d - 天 调用方法 howLong("h","2007-08-09
	 * 10:22:26","2007-08-09 20:21:30") ///9小时56分 返回9小时
	 * 
	 * @throws ParseException
	 */
	public static long howLong(String unit, String time1, String time2)
			throws ParseException {
		// 时间单位(如：不足1天(24小时) 则返回0)，开始时间，结束时间
		Date date1 = new SimpleDateFormat(FULL_DATEFORMAT).parse(time1);
		Date date2 = new SimpleDateFormat(FULL_DATEFORMAT).parse(time2);
		long ltime = date1.getTime() - date2.getTime() < 0 ? date2.getTime()
				- date1.getTime() : date1.getTime() - date2.getTime();
		if (unit.equals("s")) {
			return ltime / 1000;// 返回秒
		} else if (unit.equals("m")) {
			return ltime / 60000;// 返回分钟
		} else if (unit.equals("h")) {
			return ltime / 3600000;// 返回小时
		} else if (unit.equals("d")) {
			return ltime / 86400000;// 返回天数
		} else {
			return 0;
		}
	}

	/**
	 * 计算两段时间的差，返回格式是：1天3小时40分
	 * 
	 * @param begin
	 * @param endTime
	 * @return
	 * @throws ParseException
	 */
	public static Long[] howLong(String begin, String endTime)
			throws ParseException {
		Date date1 = new SimpleDateFormat(FULL_DATEFORMAT).parse(begin);
		Date date2 = new SimpleDateFormat(FULL_DATEFORMAT).parse(endTime);
		long ltime = date1.getTime() - date2.getTime() < 0 ? date2.getTime()
				- date1.getTime() : date1.getTime() - date2.getTime();
		return howLong(ltime);
	}

	/**
	 * 计算两段时间的差，返回格式是：1天3小时40分
	 * 
	 * @param begin
	 * @param endTime
	 * @return
	 * @throws ParseException
	 */
	public static Long[] howLong(Date begin, Date endTime) {
		long ltime = begin.getTime() - endTime.getTime() < 0 ? endTime
				.getTime()
				- begin.getTime() : begin.getTime() - endTime.getTime();
		return howLong(ltime);
	}

	/**
	 * 计算时间差 返回一个数组
	 * 
	 * @param ltime
	 *            毫秒
	 * @return 数组包含四个值：索引：0-天数，1-小时，2-分钟，3-秒 用于表示两个时间点相差 x天x小时x分钟x秒
	 */
	public static Long[] howLong(long ltime) {
		Long[] temp = new Long[4];
		Long d = ltime / 86400000;// 返回天数
		temp[0] = d;
		ltime = ltime - d * 86400000;
		Long h = ltime / 3600000;
		temp[1] = h;
		ltime = ltime - h * 3600000;
		Long m = ltime / 60000;
		temp[2] = m;
		ltime = ltime - m * 60000;
		Long s = ltime / 1000;
		temp[3] = s;
		return temp;
	}

	// 判断时间date1是否在时间date2之前或者等于
	// 时间格式 2005-4-21 16:16:34
	public static boolean isDateBeforeOrEquals(String date1, String date2) {
		try {
			DateFormat df = DateFormat.getDateTimeInstance();
			return df.parse(date1).before(df.parse(date2))
					|| df.parse(date1).equals(df.parse(date2));
		} catch (ParseException e) {
			return false;
		}
	}

	/**
	 * 转换字符串为date类型
	 * 
	 * @param time
	 * @return
	 * @throws ParseException
	 */
	public static Date parseDate(String time) throws ParseException {
		return new SimpleDateFormat(FULL_DATEFORMAT).parse(time);
	}

	/**
	 * 返回相差的时间
	 * 
	 * @param time
	 *            时间
	 * @param tim
	 *            时间
	 * @param type
	 *            类型 'h' - 小时,'m' - 分,'s' - 秒
	 * @return
	 * @throws ParseException
	 */
	public static int strDateDiffTimes(String time, int tim, char type)
			throws ParseException {
		if (null2String(time).equals("")) {
			return 1;
		}
		long diff = 1;
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new SimpleDateFormat(FULL_DATEFORMAT).parse(time));
		switch (type) {
		case 'h':
			calendar.add(Calendar.HOUR_OF_DAY, tim);
			break;
		case 'm':
			calendar.add(Calendar.MINUTE, tim);
			break;
		case 's':
			calendar.add(Calendar.SECOND, tim);
			break;
		}
		Date date = calendar.getTime();
		long ltime = getNowDate().getTime() - date.getTime();
		switch (type) {
		case 'h':
			diff = ltime / 3600000;// 返回小时
			break;
		case 'm':
			diff = ltime / 60000;// 返回分
			break;
		case 's':
			diff = ltime / 1000;// 返回秒
			break;
		}
		if (diff > Integer.MAX_VALUE) {
			return Integer.MAX_VALUE;
		} else if (diff < Integer.MIN_VALUE) {
			return Integer.MIN_VALUE;
		}
		return CommonUtil.null2Int(diff);
	}

	/**
	 * 返回相差的小时数
	 * 
	 * @param time
	 *            时间
	 * @param hours
	 *            小时
	 * @return
	 * @throws ParseException
	 */
	public static int strDateDiffHours(String time, int hours)
			throws ParseException {
		return strDateDiffTimes(time, hours, 'h');
	}

	/**
	 * 返回相差的分钟数
	 * 
	 * @param time
	 *            时间
	 * @param minutes
	 * @return
	 * @throws ParseException
	 */
	public static int strDateDiffMinutes(String time, int minutes)
			throws ParseException {
		return strDateDiffTimes(time, minutes, 'm');
	}

	/**
	 * 返回相差的秒数
	 * 
	 * @param time
	 *            时间
	 * @param minutes
	 * @return
	 * @throws ParseException
	 */
	public static int strDateDiffSeconds(String time, int sec)
			throws ParseException {
		return strDateDiffTimes(time, sec, 's');
	}

	/**
	 * 检测邮件格式
	 * 
	 * @param email
	 * @return
	 */
	public static boolean checkEmail(String email) {
		Pattern pattern = Pattern.compile("\\w+(\\.\\w+)*@\\w+(\\.\\w+)+");
		Matcher matcher = pattern.matcher(email);
		if (matcher.matches())
			return true;
		return false;
	}

	/**
	 * 转换字符串为指定编码格式
	 * 
	 * @param s
	 * @param encod
	 * 			当前字符串所用的编码方式
	 * @param encoding
	 * 			返回的编码方式
	 * @return
	 */
	public static String stringFormat(String s, String encod, String encoding) {
		try {
			return new String(s.getBytes(encod), encoding);
		} catch (UnsupportedEncodingException e) {
			return s;
		}
	}

	public static String stringFormat(String s){
		return stringFormat(s, "ISO8859-1", "UTF-8");
	}

	/**
	 * 
	 * 提供精确的小数位四舍五入处理。
	 * 
	 * @param v
	 *            需要四舍五入的数字
	 * @param scale
	 *            小数点后保留几位
	 * @return 四舍五入后的结果
	 */
	public static double round(double v, int scale) {

		if (scale < 0) {
			throw new IllegalArgumentException(
					"The scale must be a positive integer or zero");
		}

		BigDecimal b = new BigDecimal(Double.toString(v));

		BigDecimal one = new BigDecimal("1");

		return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();

	}

	/**
	 * URL编码指定字符串
	 * 
	 * @param s
	 *            字符串
	 * @return URL编码结果
	 */
	public static String urlEncode(String s) {
		try {
			return URLEncoder.encode(s, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			return s;
		}
	}

	/**
	 * URL解码指定字符串
	 * 
	 * @param s
	 *            字符串
	 * @return 解码结果
	 */
	public static String urlDecode(String s) {
		try {
			return URLDecoder.decode(s, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			return s;
		}
	}

	/**
	 * 返回指定IP是否在指定的IP数组所限定的范围内<br>
	 * IP数组内的IP地址可以使用*表示该IP段任意, 例如192.168.1.*
	 * 
	 * @param ip
	 * @param ipArry
	 * @return
	 */
	public static boolean inIPArray(String ip, String[] ipArry) {
		String[] userip = ip.split("\\.");
		for (int ipIndex = 0; ipIndex < ipArry.length; ipIndex++) {
			String[] tempip = ipArry[ipIndex].split("\\.");
			int r = 0;
			for (int i = 0; i < tempip.length; i++) {
				if (tempip[i].equals("*")) {
					return true;
				}
				if (userip.length > i) {
					if (tempip[i].equals(userip[i])) {
						r++;
					} else {
						break;
					}
				} else {
					break;
				}
			}// end for
			if (r == 4) {
				return true;
			}
		}// end for
		return false;
	}

	/**
	 * 判断指定字符串在指定字符串数组中的位置
	 * 
	 * @param strSearch
	 *            字符串
	 * @param stringArray
	 *            字符串数组
	 * @param caseInsensetive
	 *            是否不区分大小写, true为不区分, false为区分
	 * @return 字符串在指定字符串数组中的位置, 如不存在则返回-1
	 */
	public static int getInArrayID(String strSearch, String[] stringArray,
			boolean caseInsensetive) {
		for (int i = 0; i < stringArray.length; i++) {
			if (caseInsensetive) {
				if (strSearch.toLowerCase()
						.equals(stringArray[i].toLowerCase())) {
					return i;
				}
			} else {
				if (strSearch.equals(stringArray[i])) {
					return i;
				}
			}

		}
		return -1;
	}

	/**
	 * 判断指定字符串在指定字符串数组中的位置
	 * 
	 * @param strSearch
	 *            字符串
	 * @param stringArray
	 *            字符串数组
	 * @return 字符串在指定字符串数组中的位置, 如不存在则返回-1
	 */
	public static int getInArrayID(String strSearch, String[] stringArray) {
		return getInArrayID(strSearch, stringArray, true);
	}

	/**
	 * 判断指定字符串是否属于指定字符串数组中的一个元素
	 * 
	 * @param str
	 *            字符串
	 * @param stringArray
	 *            字符串数组
	 * @param caseInsensetive
	 *            是否不区分大小写, true为不区分, false为区分
	 * @return 判断结果
	 */
	public static boolean inArray(String str, String[] stringArray,
			boolean caseInsensetive) {
		return getInArrayID(str, stringArray, caseInsensetive) >= 0;
	}

	/**
	 * 判断指定字符串是否属于指定字符串数组中的一个元素
	 * 
	 * @param str
	 *            字符串
	 * @param stringArray
	 *            字符串数组
	 * @return 判断结果
	 */
	public static boolean inArray(String str, String[] stringArray) {
		return inArray(str, stringArray, false);
	}

	/**
	 * 判断指定字符串是否属于指定字符串数组中的一个元素
	 * 
	 * @param str
	 *            字符串
	 * @param stringArray
	 *            内部以指定符号分割单词的字符串
	 * @param strsplit
	 *            分割字符串
	 * @param caseInsensetive
	 *            是否不区分大小写, true为不区分, false为区分
	 * @return 判断结果
	 */
	public static boolean inArray(String str, String stringArray,
			String strsplit, boolean caseInsensetive) {
		return inArray(str, stringArray.split(strsplit), caseInsensetive);
	}

	/**
	 * 判断指定字符串是否属于指定字符串数组中的一个元素
	 * 
	 * @param str
	 *            字符串
	 * @param stringArray
	 *            内部以指定符号分割单词的字符串
	 * @param strsplit
	 *            分割字符串
	 * @return 判断结果
	 */
	public static boolean inArray(String str, String stringArray,
			String strsplit) {
		return inArray(str, stringArray.split(strsplit), false);
	}

	/**
	 * 判断指定字符串是否属于指定字符串数组中的一个元素
	 * 
	 * @param str
	 *            字符串
	 * @param stringArray
	 *            内部以逗号分割单词的字符串
	 * @return 判断结果
	 */
	public static boolean inArray(String str, String stringArray) {
		return inArray(str, stringArray.split(","), false);
	}

	/**
	 * 检测是否有sql危险字符
	 * 
	 * @param str
	 *            要判断字符串
	 * @return 判断结果
	 */
	public static boolean isSafeSqlString(String str) {
		Pattern pattern = Pattern
				.compile("[-|;|,|/|(|)|\\[|\\]|\\}|\\{|%|@|\\*|!|\\']");
		return !pattern.matcher(str).find();
	}

	/**
	 * 返回文件是否存在
	 * 
	 * @param filePath
	 *            文件名
	 * @return 是否存在
	 */
	public static boolean fileExists(String filePath) {
		File file = new File(filePath);
		return file.exists();
	}

	/**
	 * 创建文件夹
	 * 
	 * @param filePath
	 * @return true:创建文件夹成功 false：创建失败
	 */
	public static boolean createFolder(String filePath) {
		File file = new File(filePath);
		return file.mkdir();
	}

	/**
	 * 删除文件或文件夹，
	 * 
	 * @param filePath
	 *            文件的完整路径
	 * @return 删除成功返回TRUE 删除失败返回 FALSE
	 */
	public static boolean deleteFile(String filePath) {
		if (filePath != null && !"".equals(filePath)) {
			File file = new File(filePath);
			if (file.exists()) {
				return file.delete();
			}
		}
		return false;
	}

	/**
	 * 将字符串转换为Color
	 * 
	 * @param color
	 * @return
	 */
	public static Color toColor(String color) {
		int red, green, blue = 0;
		char[] rgb;
		color = "#" + color.trim();
		color = color.toLowerCase().replaceAll("[g-zG-Z]", "");
		switch (color.length()) {
		case 3:
			rgb = color.toCharArray();
			red = CommonUtil.null2Int(rgb[0] + "" + rgb[0], 16);
			green = CommonUtil.null2Int(rgb[1] + "" + rgb[1], 16);
			blue = CommonUtil.null2Int(rgb[2] + "" + rgb[2], 16);
			return new Color(red, green, blue);
		case 6:
			rgb = color.toCharArray();
			red = CommonUtil.null2Int(rgb[0] + "" + rgb[1], 16);
			green = CommonUtil.null2Int(rgb[2] + "" + rgb[3], 16);
			blue = CommonUtil.null2Int(rgb[4] + "" + rgb[5], 16);
			return new Color(red, green, blue);
		default:
			return Color.decode(color);
		}
	}

	/**
	 * 为脚本替换特殊字符串
	 * 
	 * @param str
	 * @return
	 */
	public static String replaceStrToScript(String str) {
		str = str.replace("\\", "\\\\");
		str = str.replace("'", "\\'");
		str = str.replace("\"", "\\\"");
		return str;
	}

	/**
	 * 判断文件名是否为浏览器可以直接显示的图片文件名
	 * 
	 * @param filename
	 *            文件名
	 * @return 是否可以直接显示
	 */
	public static boolean isImgFilename(String filename) {
		filename = filename.trim();
		if (filename.endsWith(".") || filename.indexOf(".") == -1) {
			return false;
		}
		String extname = filename.substring(filename.lastIndexOf(".") + 1)
				.toLowerCase();
		return (extname.equals("jpg") || extname.equals("jpeg")
				|| extname.equals("png") || extname.equals("bmp") || extname
				.equals("gif"));

	}

	/**
	 * 判断是否为允许上传的文件
	 * 
	 * @param filename
	 * @return
	 */
	public static boolean isAllowFileName(String filename) {
		filename = filename.trim();
		if (filename.endsWith(".") || filename.indexOf(".") == -1) {
			return false;
		}
		String extname = filename.substring(filename.lastIndexOf(".") + 1)
				.toLowerCase();
		return (extname.equals("doc") || extname.equals("docx")
				|| extname.equals("rtf") || extname.equals("xls"));
	}

	/**
	 * 获得文件后缀名 返回的后缀名带有"."
	 * 
	 * @param fileName
	 * @return
	 */
	public static String getExtention(String fileName) {
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(pos);
	}

	/**
	 * 文件采用UUID重命名
	 * 
	 * @param oldName
	 * @return
	 */
	public static String renameFile(String oldName) {
		return UUID.randomUUID().toString() + getExtention(oldName);
	}

	/**
	 * 按照规则重命名
	 * 
	 * @param oldName
	 *            原来名字 xxx.jpg
	 * @param reFormat
	 *            格式 xxx-s.jpg
	 * @return
	 */
	public static String renameFile(String oldName, String reFormat) {
		int pos = oldName.lastIndexOf(".");
		String tmp = oldName.substring(0, pos);
		return tmp + "-" + reFormat + getExtention(oldName);
	}

	/**
	 * 检测是否为IP
	 * 
	 * @param ip
	 * @return
	 */
	public static boolean isIPSect(String ip) {
		return Pattern
				.compile(
						"^((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){2}((2[0-4]\\d|25[0-5]|[01]?\\d\\d?|\\*)\\.)(2[0-4]\\d|25[0-5]|[01]?\\d\\d?|\\*)$")
				.matcher(ip).find();

	}

	/**
	 * 判断是否为时间
	 * 
	 * @param timeval
	 * @return
	 */
	public static boolean isTime(String timeval) {
		return Pattern.compile(
				"^((([0-1]?[0-9])|(2[0-3])):([0-5]?[0-9])(:[0-5]?[0-9])?)$")
				.matcher(timeval).find();
	}

	/**
	 * 将字符串转为16进制
	 * 
	 * @param s
	 * @return
	 */
	public static String toHexString(String s) {
		String str = "";
		for (int i = 0; i < s.length(); i++) {
			int ch = (int) s.charAt(i);
			String s4 = Integer.toHexString(ch);
			str = str.concat(s4);
		}
		return "0x" + str;// 0x表示十六进制
	}


	/**
	 * 将十六进制字符串转为字符串
	 * 
	 * @param s
	 * @return
	 */
	public static String toStringHex(String s) {
		if ("0x".equals(s.substring(0, 2))) {
			s = s.substring(2);
		}
		byte[] baKeyword = new byte[s.length() / 2];
		for (int i = 0; i < baKeyword.length; i++) {
			try {
				baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(
						i * 2, i * 2 + 2), 16));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {
			s = new String(baKeyword, "utf-8");// UTF-16le:Not
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return s;
	}

	/**
	 * 求两个日期之间相差的月数
	 * 
	 * @param strDate1
	 *            开始时间
	 * @param strDate2
	 *            结束时间
	 * @return
	 */
	public static int prayIntervalMonths(Date beginDate, Date endDate) {
		int iMonth = 0;
		int flag = 0;
		try {
			Calendar objCalendarDate1 = Calendar.getInstance();
			objCalendarDate1.setTime(beginDate);

			Calendar objCalendarDate2 = Calendar.getInstance();
			objCalendarDate2.setTime(endDate);

			if (objCalendarDate2.equals(objCalendarDate1))
				return 0;
			if (objCalendarDate1.after(objCalendarDate2)) {
				Calendar temp = objCalendarDate1;
				objCalendarDate1 = objCalendarDate2;
				objCalendarDate2 = temp;
			}
			if (objCalendarDate2.get(Calendar.DAY_OF_MONTH) < objCalendarDate1
					.get(Calendar.DAY_OF_MONTH))
				flag = 1;

			if (objCalendarDate2.get(Calendar.YEAR) > objCalendarDate1
					.get(Calendar.YEAR))
				iMonth = ((objCalendarDate2.get(Calendar.YEAR) - objCalendarDate1
						.get(Calendar.YEAR))
						* 12 + objCalendarDate2.get(Calendar.MONTH) - flag)
						- objCalendarDate1.get(Calendar.MONTH);
			else
				iMonth = objCalendarDate2.get(Calendar.MONTH)
						- objCalendarDate1.get(Calendar.MONTH) - flag;

		} catch (Exception e) {
		}
		return iMonth;
	}

	/**
	 * 编码html代码段，主要替换 尖括号
	 * 
	 * @param htmlStr
	 * @return
	 */
	public static String htmlEncode(String htmlStr) {
		if (htmlStr == null) {
			return null;
		}
		String text = htmlStr.replaceAll("<", "&lt;");
		text = text.replaceAll(">", "&gt;");
		return text;
	}

	/**
	 * 返回友好的时间格式
	 * 
	 * @param time
	 * @return 刚刚/x分钟以前
	 */
	public static String friendlyTime(Date time) {
		if (time == null)
			return "未知时间";
		int ct = (int) ((System.currentTimeMillis() - time.getTime()) / 1000);
		if (ct < 60)
			return "刚刚";
		if (ct < 3600)
			return Math.max(ct / 60, 1) + "分钟以前";
		if (ct >= 3600 && ct < 86400)
			return ct / 3600 + "小时以前";
		if (ct >= 86400 && ct < 2592000) {
			int day = ct / 86400;
			if (day > 1) {
				return day + "天以前";
			} else {
				return "昨天";
			}
		}
		if (ct >= 2592000 && ct < 31104000)
			return ct / 2592000 + "月以前";
		return ct / 31104000 + "年以前";
	}
	/**
     * ip校验
     * @param s
     * @return
     */
    public static Boolean isIpAddress(String s){
            String regex = "(((2[0-4]\\d)|(25[0-5]))|(1\\d{2})|([1-9]\\d)|(\\d))[.](((2[0-4]\\d)|(25[0-5]))|(1\\d{2})|([1-9]\\d)|(\\d))[.](((2[0-4]\\d)|(25[0-5]))|(1\\d{2})|([1-9]\\d)|(\\d))[.](((2[0-4]\\d)|(25[0-5]))|(1\\d{2})|([1-9]\\d)|(\\d))";
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(s);
            return m.matches();
    }
    /**
     * 获取客户端ip
     * @param request
     * @return
     */
    public static String getClientAddress(HttpServletRequest request) {
        String address = request.getHeader("X-Forwarded-For");
        if (address != null && isIpAddress(address)) {
            return address;
        }
        return request.getRemoteAddr();
    }
    
	
	/**
	 * 转换字符串为date类型
	 * 
	 * @param time
	 * @return    yyyy-mm-dd
	 * @throws ParseException
	 */
	public static Date parseShortDate(String time) throws ParseException {
		return new SimpleDateFormat(SHORT_DATEFORMAT).parse(time);
	}
	
	
	/**
	 * 检查指定的元素是否在数组里面
	 * @param items
	 * @param item
	 * @return
	 */
	public static boolean hasInArray(String[] items,String item){
		for(String in : items){
			if(in.equals(item)){
				return true;
			}
		}
		
		return false;
	}
	
	/**
	 * String 转换 Long
	 */
	public static Long[] stringOfLong(String ids){
		String []idArr = ids.split("-");
		Long []idList = new Long[idArr.length];
		for(int i = 0;i<idArr.length;i++){
			if(idArr[i] != ""){
				idList[i] = Long.valueOf(idArr[i]);
			}
		}
		return idList;
	}

	/**
	 * String 转换 Integer
	 */
	public static Integer[] stringOfInteger(String ids){
		String []idArr = ids.split("-");
		Integer []idList = new Integer[idArr.length];
		for(int i = 0;i<idArr.length;i++){
			if(idArr[i] != ""){
				idList[i] = Integer.valueOf(idArr[i]);
			}
		}
		return idList;
	}
	/**
	 * 取出文件名
	 * @param fileName
	 * @return
	 */
	public static String getLastName(String fileName) {
		int pos = fileName.lastIndexOf("\\");
		if (pos > -1) {
			fileName = fileName.substring(pos + 1);
		}
		pos = fileName.lastIndexOf("/");
		if (pos > -1) {
			fileName = fileName.substring(pos + 1);
		}
		return fileName;
	}
	/**
	 * 转义 特殊符
	 * @param condition
	 * @return
	 */
	public static String escapeSpecialSign(String condition){
		String bb = StringUtils.replace(condition, "/", "//");
		bb = StringUtils.replace(bb, "%", "/%");
		bb = StringUtils.replace(bb, "_", "/_");
		return bb;
	}
	/**
	 * 获得给定文件的后缀名
	 * 
	 * @param tempName
	 * @return
	 */
	public static String getExt(String tempName) {
		if (StringUtils.isNotBlank(tempName)) {
			return tempName.substring(tempName.lastIndexOf(".") + 1, tempName
					.length());
		}
		return null;
	}
	
	/**
	 * 生成短信验证码 随即6位数字
	 * 
	 * @return 短信验证码
	 */
	public static String makeMobileCaptcha() {
		String[] arr = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
		Random random = new Random();
		StringBuffer bu = new StringBuffer();
		while (bu.length() < 6) {
			String temp = arr[random.nextInt(10)];
			if (bu.indexOf(temp) == -1) {
				bu.append(temp);
			}
		}

		return bu.toString();
	}
	
	/**
	 * 去除html代码
	 * 
	 * @param inputString
	 * @return
	 */
	public static String htmlToText(String htmlStr) {
		if(htmlStr == null){
			return null;
		}
		String textStr = "";
		java.util.regex.Pattern p_script;
		java.util.regex.Matcher m_script;
		java.util.regex.Pattern p_style;
		java.util.regex.Matcher m_style;
		java.util.regex.Pattern p_html;
		java.util.regex.Matcher m_html;
		java.util.regex.Pattern p_ba;
		java.util.regex.Matcher m_ba;

		try {
			String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
			// }
			String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
			// }
			String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
			String patternStr = "\\s+";
			p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
			m_script = p_script.matcher(htmlStr);
			htmlStr = m_script.replaceAll(""); // 过滤script标签
			p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
			m_style = p_style.matcher(htmlStr);
			htmlStr = m_style.replaceAll(""); // 过滤style标签
			p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(htmlStr);
			htmlStr = m_html.replaceAll(""); // 过滤html标签
			p_ba = Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE);
			m_ba = p_ba.matcher(htmlStr);
			htmlStr = m_ba.replaceAll(""); // 过滤空格
			textStr = htmlStr;
		} catch (Exception e) {
			e.printStackTrace();
			Logger.getLogger(CommonUtil.class.getName()).log(Level.SEVERE, null, e);
		}
		return textStr;// 返回文本字符串
	}
	/**
	 * 判断是否是乱码
	 * @param strName
	 * @return
	 */
	 public static boolean isMessyCode(String strName) {  
	        Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*");  
	        Matcher m = p.matcher(strName);  
	        String after = m.replaceAll("");  
	        String temp = after.replaceAll("\\p{P}", "");  
	        char[] ch = temp.trim().toCharArray();  
	        float chLength = 0 ;  
	        float count = 0;  
	        for (int i = 0; i < ch.length; i++) {  
	            char c = ch[i];  
	            if (!Character.isLetterOrDigit(c)) {  
	                if (!isChinese(c)) {  
	                    count = count + 1;  
	                }  
	                chLength++;   
	            }  
	        }  
	        float result = count / chLength ;  
	        if (result > 0.4) {  
	            return true;  
	        } else {  
	            return false;  
	        }  
	    }  
	 private static boolean isChinese(char c) {  
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);  
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS  
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS  
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A  
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION  
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION  
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {  
            return true;  
        }  
        return false;  
	  }  

	/** 
     * 两个时间相差距离多少天多少小时多少分多少秒 
     * @param str1 时间参数 1 格式：1990-01-01 12:00:00 
     * @param str2 时间参数 2 格式：2009-01-01 12:00:00 
     * @return String 返回值为：xx天xx小时xx分xx秒 
     */  
    public static String getDistanceTime(Date str1, Date str2) {  
        long day = 0;  
        long hour = 0;  
        long min = 0;  
        long time1 = str1.getTime();  
		long time2 = str2.getTime();  
		long diff ;  
		if(time1<time2) {  
		    diff = time2 - time1;  
		} else {  
		    diff = time1 - time2;  
		}  
		day = diff / (24 * 60 * 60 * 1000);  
		hour = (diff / (60 * 60 * 1000) - day * 24);  
		min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);  
        String result = "";
        if(day>0){
        	 result+=day + "天";
        }
        if(hour>0){
         	result+=hour + "小时";
        }
        if(min>0){
         	result+=min + "分钟";
        }else if(min == 0){
        	result+="1分钟";
        }
        return result+"前";  
    } 
    /**
     * 裁剪图片
     * @param src
     * @param dest
     * @param x
     * @param y
     * @param w
     * @param h
     * @throws IOException
     */
    @SuppressWarnings("rawtypes")
	public static void cutImage(String src,String dest,int x,int y,int w,int h,String fileExt) throws IOException{   
        Iterator iterator = ImageIO.getImageReadersByFormatName(fileExt);   
        ImageReader reader = (ImageReader)iterator.next();   
        InputStream in=new FileInputStream(src);  
        ImageInputStream iis = ImageIO.createImageInputStream(in);   
        reader.setInput(iis, true);   
        ImageReadParam param = reader.getDefaultReadParam();   
        Rectangle rect = new Rectangle(x, y, w,h);    
        param.setSourceRegion(rect);   
        BufferedImage bi = reader.read(0,param);     
        ImageIO.write(bi, fileExt, new File(dest));             
    }
    /* 
     * 图片缩放 
     */  
    @SuppressWarnings("static-access")
	public static void zoomImage(String src,String dest,int w,int h) throws Exception {  
        double wr=0,hr=0;  
        File srcFile = new File(src);  
        File destFile = new File(dest);  
        BufferedImage bufImg = ImageIO.read(srcFile);  
        Image Itemp = bufImg.getScaledInstance(w, h, bufImg.SCALE_SMOOTH);  
        wr=w*1.0/bufImg.getWidth();  
        hr=h*1.0 / bufImg.getHeight();  
        AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(wr, hr), null);  
        Itemp = ato.filter(bufImg, null);  
        try {  
            ImageIO.write((BufferedImage) Itemp,dest.substring(dest.lastIndexOf(".")+1), destFile);  
        } catch (Exception ex) {  
            ex.printStackTrace();  
        }  
          
    }
    /**
     * 得到图片的宽高
     * @param src
     * @return
     * @throws IOException
     */
    public static int[] getImageWAndH(String src) throws IOException{
    	File srcFile = new File(src);  
    	BufferedImage bufImg = ImageIO.read(srcFile);
    	return new int[]{bufImg.getWidth(),bufImg.getHeight()};
    }
	 
}
